﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace Sern.Common
{
    public static class ObjectHasher
    {
        public static Guid GetHashGuid(this object @object)
        {
            byte[] md5Hash = new byte[]{};
            using (var serializingStream = new MemoryStream())
            {
                var serializer = new NetDataContractSerializer();
                var md5 = new MD5CryptoServiceProvider();

                serializer.WriteObject(serializingStream, @object);                                
                md5Hash = md5.ComputeHash(serializingStream); 
            }

            return new Guid(md5Hash);
        }

        public static Guid GetHashGuidFromEnumerable(this IEnumerable<object> objects)
        {
            byte[] md5Hash = new byte[] { };
            using (var serializingStream = new MemoryStream())
            {
                var serializer = new NetDataContractSerializer();
                var md5 = new MD5CryptoServiceProvider();
                foreach (var @object in objects)
                {
                    serializer.WriteObject(serializingStream, @object);
                }
                md5Hash = md5.ComputeHash(serializingStream);
            }

            return new Guid(md5Hash);
        }
    }
}
